package com.wtc.houserent.service;

import com.wtc.houserent.model.House;

/**
 * HouseService.java <=> 类 [业务层]
 * 定义House[]，保存House对象
 * 1.响应HouseView的调用
 * 2.完成对房屋信息的各种操作（增删改查crud）
 */
public class HouseService {
    private House[] houses;
    private House[] housesNew;
    private int houseNum = 1;
    private int idCounter = 1;

    //数组：存储房源信息
    public HouseService(int size) {
        houses = new House[size];//当创建HouseService时指定数组大小
        //测试数组
        houses[0] = new House(1, "马可", "176", "洪山区", 2000, "已出租");
    }

    public House[] house() {
        return houses;
    }

    //存储新添加的房源信息
    public boolean add(House newHouse) {
        if (houseNum == houses.length) {
            housesNew = new House[houses.length + 1];
            for (int i = 0; i < houses.length; i++) {
                housesNew[i] = houses[i];
            }
            houses = housesNew;
        }
        houses[houseNum++] = newHouse;
        newHouse.setId(++idCounter);
        return true;
    }

    //删除房源信息
    public boolean del(int delId) {
        int index = -1;
        for (int i = 0; i < houseNum; i++) {
            if (delId == houses[i].getId()) {
                index = i;
            }
        }

        if (index == -1) {
            return false;
        }

        for (int i = 0; i < (houseNum - 1); i++) {
            houses[i] = houses[i + 1];
        }
        houses[--houseNum] = null;
        return true;
    }
    //搜索房源信息
    public boolean select(int selectId) {
        int index = -1;
        for (int i = 0; i < houseNum; i++) {
            if (selectId == houses[i].getId()) {
                index = i;
            }
        }
        if (index == -1) {
            return false;
        }
        System.out.println(houses[index]);
        return true;
    }
    //修改房屋信息功能
    public House update(int updateId) {
        int index = -1;
        for (int i = 0; i < houseNum; i++) {
            if (updateId == houses[i].getId()) {
               index = i;
            }
        }
        if (index == -1) {
            return null;
        }
        return houses[index];
    }
}
